//
//  HLToModelExtention.swift
//  SwiftPods
//
//  Created by hulinhu on 2018/1/17.
//  Copyright © 2018年 hulinhu. All rights reserved.

//  JSON 转换为 模型
import Foundation
import RxSwift
import RxCocoa
import Moya
import ObjectMapper
import SwiftyJSON
import RxAlamofire

// 忽略false
extension Observable where Element: Equatable {
    func ignore(value: Element) -> Observable<Element> {
        return filter { (e) -> Bool in
            return value != e
        }
    }
}

extension Observable {
    
    // 字典映射
    func mapObject<T:Mappable>(type: T.Type) -> Observable<T> {
        return self.map({ response in
            guard let dict = response as? [String:Any] else {
                throw  RxSwiftMoyaError.ParseJSONError
            }
            return Mapper<T>().map(JSON: dict)!
        })
    }
    // 数组映射
    func mapArray<T: Mappable>(type: T.Type) -> Observable<[T]> {
        return self.map { response in
            //if response is an array of dictionaries, then use ObjectMapper to map the dictionary
            //if not, throw an error
            guard let array = response as? [Any] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
            guard let dicts = array as? [[String: Any]] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
            return Mapper<T>().mapArray(JSONArray: dicts)
        }
    }
}

enum RxSwiftMoyaError: String {
    case ParseJSONError
    case OtherError
}

extension RxSwiftMoyaError: Swift.Error { }

